import 'package:flutter/cupertino.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:get/get.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/home/inner_video/inner_video_panel.dart';
import 'package:ball_lion/widgets/player/qs_player_logic.dart';
import 'package:ball_lion/widgets/player/qs_player.dart';
import 'package:ball_lion/module/overlay/live_float_widget.dart';

class InnerVideoWidget extends StatefulWidget {
  const InnerVideoWidget(
      {super.key, required this.logic, required this.extensionContext});

  final QsPlayerLogic logic;
  final ExtensionContext extensionContext;

  @override
  State<InnerVideoWidget> createState() => _InnerVideoWidgetState();
}

class _InnerVideoWidgetState extends State<InnerVideoWidget> {
  QsPlayerLogic get logic => widget.logic;
  double? width;
  double? height;

  @override
  void initState() {
    LiveFloatController.instance.off();
    final attributes = widget.extensionContext.attributes;
    final sources = <String?>[
      if (attributes['src'] != null) attributes['src'],
      ...ReplacedElement.parseMediaSources(
          widget.extensionContext.node.children),
    ];
    final givenWidth = double.tryParse(attributes['width'] ?? "");
    final givenHeight = double.tryParse(attributes['height'] ?? "");
    width = givenWidth ?? Get.width;
    height = givenHeight ?? (Get.width * 9 / 16);
    if (sources.isNotEmpty && sources.first != null) {
      Uri sourceUri = Uri.parse(sources.first!);
      if (logic.url.noValue) {
        logic.url = sourceUri.toString();
      }
    }
    super.initState();
  }

  @override
  void didChangeDependencies() {
    logic.addListener(() {
      if (mounted) {
        setState(() {});
      }
    });
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: Get.width,
      height: Get.width * 188 / 335,
      child: Stack(
        children: [
          QsPlayer(logic: logic),
          InnerVideoPanel(context: widget.extensionContext, logic: logic)
        ],
      ),
    );
  }
}
